// pages/search/index.js
import {request} from "../../util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    history:[],
    historyShow:true,
    keyword:undefined,
    orderIndex:0,
    orderItems:[],
    goods:[],
    pageNum:1,
    pageSize:10,
  },
  onChange(e){
    this.setData({keyword:e.detail})
  },
  onFocus(e){
    this.setData({historyShow:true})
  },
  onSearch(){
    if(!this.data.keyword|| this.data.keyword.length===0){
      return
    }
    this.setData({pageNum:1,goods:[]})
    let history= this.data.history
    history.unshift(this.data.keyword)
    history= [...new Set(history)]
    this.setData({
      history:history
    })
    wx.setStorageSync('goodsHistory', history)
    this.setData({historyShow:false})
    //搜索逻辑
    this.loadGoods()
  },
  cleanHistory(){
    this.setData({history:[]})
  },
  clickHistoryItem(e){
    let item=e.currentTarget.dataset.id
    this.setData({keyword:item})
    //搜索逻辑
    this.onSearch()
  },
  clickOrder(e){
    let orderIndex=  parseInt(e.currentTarget.dataset.index)
    this.setData({orderIndex})
    if(orderIndex===0){
      this.setData({orderItems:[]})
    }else if(orderIndex===1){
      this.setData({
        orderItems:[{column:"sales",asc:false}]
      })
    }else if(orderIndex===2){
      this.setData({
        orderItems:[{column:"price",asc:true}]
      })
    }else if(orderIndex===3){
      this.setData({
        orderItems:[{column:"updated_time",asc:false}]
      })
    }
    this.onSearch()
  },
  loadGoods(){
    request({
      url:"/goods/search",
      method:"POST",
      data:{
        key:this.data.keyword,
        orderItems:this.data.orderItems,
        pageNum:this.data.pageNum,
        pageSize:this.data.pageSize
      }
    }).then(res=>{
      let goods= this.data.goods.concat(res.data.list)
      this.setData({goods})
      if(this.data.pageNum>res.data.pages ){
        this.setData({pageNum:res.data.pages})
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let history= wx.getStorageSync('goodsHistory')|| []
    this.setData({history})
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log("触底了");
    this.setData({pageNum: this.data.pageNum+1})
    this.loadGoods()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})